package com.atjinggu.jinggumail.cart.interceptor;

import com.atjinggu.jinggumail.cart.vo.UserInfoTo;
import com.atjinggu.jinggumail.common.constant.AuthConstant;
import com.atjinggu.jinggumail.common.constant.CartConstant;
import com.atjinggu.jinggumail.common.vo.MemberResponseVo;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author jingming
 * @Type CartInterceptor.java
 * @Desc
 * @date 2021/3/5 14:08
 */
public class CartInterceptor implements HandlerInterceptor {

    public static  ThreadLocal<UserInfoTo> threadLocal =  new ThreadLocal();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberResponseVo member = (MemberResponseVo) session.getAttribute(AuthConstant.LOGIN_USER);
        UserInfoTo userInfoTo = new UserInfoTo();
        if(member != null){
            userInfoTo.setUserId(member.getId() +"");
        }
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length > 0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.CART_USER_TOKEN)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTmpUser(true);
                }
            }
        }
        if(userInfoTo.getUserKey() == null){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }

        threadLocal.set(userInfoTo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        if(!userInfoTo.isTmpUser()){
            Cookie cookie = new Cookie(CartConstant.CART_USER_TOKEN, userInfoTo.getUserKey());
            cookie.setDomain("jinggumail.com");
            cookie.setMaxAge(CartConstant.CART_USER_TOKEN_MAX_TIME);
            response.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        threadLocal.remove();
    }
}